#include "sylar/sylar.h"


#include <sys/types.h>
#include <sys/socket.h>
#include <sys/unistd.h>
#include <fcntl.h>
#include <arpa/inet.h>

sylar::Logger::LoggerPtr g_logger = SYLAR_LOG_ROOT();

void test_fiber()
{
    SYLAR_LOG_ERROR(g_logger) << "test_fiber";

    int sock = ::socket(AF_INET, SOCK_STREAM, 0);
    fcntl(sock, F_SETFL, O_NONBLOCK);

    sockaddr_in addr;
    memset(&addr, 0, sizeof(sockaddr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(80);
    // ping www.baidu.com
    inet_pton(AF_INET, "183.2.172.185", &addr.sin_addr.s_addr);

    

    if (!::connect(sock, (sockaddr*)&addr, sizeof(addr)))
    {

    }
    else if (errno == EINPROGRESS)
    {
        SYLAR_LOG_INFO(g_logger) << "add evert errno:" << errno << " " << strerror(errno);
        sylar::IOManger::GetThis()->addEvent(sock, sylar::IOManger::READ, [](){
            SYLAR_LOG_INFO(g_logger) << "read callback";
        });

        sylar::IOManger::GetThis()->addEvent(sock, sylar::IOManger::WRITE,[sock]()
        {
            SYLAR_LOG_INFO(g_logger) << "write callback";
            //close(sock); 主动关闭不会触发 read callback
            sylar::IOManger::GetThis()->cancelEvent(sock, sylar::IOManger::READ);
            close(sock);
        });
    }
    else 
    {
        SYLAR_LOG_INFO(g_logger) << "else " << errno << " " << strerror(errno);
    }
}

void test1()
{
    sylar::IOManger iom(2, false);
    iom.schedule(&test_fiber);
}

sylar::Timer::ptr s_timer;
void test_timer()
{
    sylar::IOManger iom(2);
    s_timer = iom.addTimer(1000, [](){
        static int i = 0;
        SYLAR_LOG_ERROR(g_logger) << "hello time i = " << i;
        if (++i == 3)
        {
            //s_timer->cancel();
            s_timer->reset(2000, true);
        }

    }, true);
}

int main(int argc, char* argv[])
{

    //test1();
    test_timer();

    return 0;
}